<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>适配器模式典型应用之数据格式化</title>
</head>
<body>
    <form>
        <select id="users"></select>
        <button>注册</button>
    </form>
    <script>
        //适配器模式典型应用之数据格式化

        //这是服务端返回的数据
        let treeData = [
            {
            name:'山东',
            key:'shandong',
            children:[
                {name:'青岛',key:'qingdao'},
                {name:'济南',key:'jinan'}
            ]
            },
            {
            name:'浙江',
            key:'zhejiang',
            children:[
                {name:'丽水',key:'lishui'},
                {name:'杭州',key:'hangzhou'}
            ]
            }
        ];

        //通过适配器将数据变成[山东，青岛，济南，浙江，丽水，杭州]格式
        //格式转换适配器
        function flattenAdaptor(treeData,array) { 
            treeData.filter(item=>{
                array.push({name:item.name,key:item.key}) ;
                if(item.children){
                     flattenAdaptor(item.children,array)
                }
               
            });
            return array
         };
         let users = document.getElementById('users');
         //数据适配转换格式
         let resArr = flattenAdaptor(treeData,[]);
         let elemsArr = resArr.map(item=>{
             return `<option value=${item.key}>${item.name}<option>`
         });
         let elems = elemsArr.join("");
         console.log('elsms是',elems);
         users.innerHTML=elems;



    </script>
    
</body>
</html>